﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Resources;
using System.Web.UI.WebControls;
using ShopBLL;
using ShopModel;

public partial class LanguageEdit : System.Web.UI.Page
{

    #region CONSTANTS

    private const string LANGUAGE_ID = "EditLanguageID";
    private const string DEFAULT_LANGUAGE_CULTURE = "DefaultLanguageCulture";
    private const string EDIT_LANGUAGE_CULTURE = "EditLanguageCulture";

    #endregion CONSTANTS

    #region VARIABLES

    DataTable _dtEditedResources;

    #endregion VARIABLES

    #region PROPERTIES

    DataTable dtEditedResources
    {
        get
        {
            if (_dtEditedResources == null)
            {
                if (Session["EditedResources"] != null)
                {
                    _dtEditedResources = (DataTable)Session["EditedResources"];
                }
                else
                {

                    DataColumn[] dc = new DataColumn[1];
                    dc[0] = new DataColumn("Key");
                    _dtEditedResources = new DataTable("EditedResources");
                    _dtEditedResources.Columns.Add(dc[0]);
                    _dtEditedResources.Columns.Add(new DataColumn("Default"));
                    _dtEditedResources.Columns.Add(new DataColumn("Selected"));

                    _dtEditedResources.PrimaryKey = dc;
                }
            }

            return _dtEditedResources;
        }

        set
        {
            _dtEditedResources = value;
            Session["EditedResources"] = _dtEditedResources;
        }
    }

    #endregion PROPERTIES

    #region METHODS

    protected void BindLanguages()
    {
        List<Language> langList = ReportsManager.Instance.GetAvailableLanguages(false);
        langList.RemoveAll(delegate(Language l) { return l.IsDefault; });
        ddlLanguage.DataSource = langList;
        ddlLanguage.DataBind();
    }

    protected void BindResources()
    {
        ResXResourceReader resxReader = new ResXResourceReader(Server.MapPath("../App_GlobalResources/Language.resx"));
        ResXResourceSet resxResourceSet = new ResXResourceSet(Server.MapPath("../App_GlobalResources/Language." + ddlLanguage.SelectedValue + ".resx"));
        string s;

        DataSet dsResources = new DataSet();

        dsResources.Tables.Add(new DataTable("Resources"));

        DataColumn[] dc = new DataColumn[1];
        dc[0] = new DataColumn("Key");

        dsResources.Tables["Resources"].Columns.Add(dc[0]);
        dsResources.Tables["Resources"].Columns.Add(new DataColumn("Default"));
        dsResources.Tables["Resources"].Columns.Add(new DataColumn("Selected"));
        dsResources.Tables["Resources"].PrimaryKey = dc;

        foreach (DictionaryEntry de in resxReader)
        {
            DataRow dr = dtEditedResources.Rows.Find(de.Key.ToString());

            if (dr != null)
            {
                dsResources.Tables["Resources"].Rows.Add(dr["Key"], dr["Default"], dr["Selected"]);
            }
            else
            {
                s = resxResourceSet.GetString(de.Key.ToString());
                dsResources.Tables["Resources"].Rows.Add(de.Key, de.Value, s);
            }
        }

        foreach (DictionaryEntry de in resxResourceSet)
        {
            DataRow dr = dsResources.Tables["Resources"].Rows.Find(de.Key.ToString());

            if (dr == null)
            {
                dsResources.Tables["Resources"].Rows.Add(de.Key, string.Empty, de.Value);
            }
        }

        gvResources.DataSource = dsResources;
        gvResources.DataBind();
    }

    protected void SaveResources()
    {
        if (dtEditedResources.Rows.Count > 0)
        {
            ResXResourceReader resxReader = new ResXResourceReader(Server.MapPath("../App_GlobalResources/Language.resx"));
            ResXResourceSet resxResourceSet = new ResXResourceSet(Server.MapPath("../App_GlobalResources/Language." + ddlLanguage.SelectedValue + ".resx"));
            string s;

            DataSet dsResources = new DataSet();

            dsResources.Tables.Add(new DataTable("Resources"));

            dsResources.Tables["Resources"].Columns.Add(new DataColumn("Key"));
            dsResources.Tables["Resources"].Columns.Add(new DataColumn("Default"));
            dsResources.Tables["Resources"].Columns.Add(new DataColumn("Selected"));

            foreach (DictionaryEntry de in resxReader)
            {
                DataRow dr = dtEditedResources.Rows.Find(de.Key.ToString());

                if (dr != null)
                {
                    dsResources.Tables["Resources"].Rows.Add(dr["Key"], dr["Default"], dr["Selected"]);
                }
                else
                {
                    s = resxResourceSet.GetString(de.Key.ToString());
                    dsResources.Tables["Resources"].Rows.Add(de.Key, de.Value, s);
                }
            }

            gvResources.DataSource = dsResources;
            gvResources.DataBind();

            resxReader.Close();
            resxResourceSet.Close();

            ResXResourceWriter resxDefaultWriter = new ResXResourceWriter(Server.MapPath("../App_GlobalResources/Language.resx"));
            ResXResourceWriter resxSelectedWriter = new ResXResourceWriter(Server.MapPath("../App_GlobalResources/Language." + ddlLanguage.SelectedValue + ".resx"));

            string def, sel;
            DataRow[] sorted = dsResources.Tables["Resources"].Select(null,"Key");


            foreach (DataRow dr in sorted)
            {
                def = dr["Default"].ToString();
                sel = dr["Selected"].ToString();
                resxDefaultWriter.AddResource(dr["Key"].ToString(), def);
                if (sel != string.Empty)
                    resxSelectedWriter.AddResource(dr["Key"].ToString(), sel);
            }

            resxDefaultWriter.Close();
            resxSelectedWriter.Close();

            Session["EditedResources"] = null;
        }
    }

    private void gvLanguagesDataBind()
    {
        rptLanguages.DataSource = ReportsManager.Instance.GetAvailableLanguages(false);
        rptLanguages.DataBind();
    }

    private void ClearNewLanguageRow()
    {
        LangNameTB.Text = string.Empty;
        LangCultureTB.Text = string.Empty;
        LangActiveCB.Checked = false;
        LangFlagUrlTB.Text = string.Empty;
        LangIsDefaultCB.Checked = false;
        LangAddBTN.Text = Resources.Language.Add;
        LangCancelBTN.Text = Resources.Language.Cancel;
        Session[LANGUAGE_ID] = null;
    }

    private void ddlCountryDataBind()
    {
        ddlDefaultCountry.DataSource = ReportsManager.Instance.GetCountries(CommonTools.CurrentLanguageID);
        ddlDefaultCountry.DataBind();
        ddlDefaultCountry.SelectedValue = ShopModel.Settings.DefaultCountry.ToString();
    }

    #endregion METHODS

    #region EVENTS

    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvResources.EditIndex = -1;
        Session["EditedResources"] = null;
        BindResources();
    }

    protected void gvResources_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvResources.EditIndex = e.NewEditIndex;
        BindResources();
    }

    protected void gvResources_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string key = gvResources.Rows[e.RowIndex].Cells[0].Text;
        string def = (gvResources.Rows[e.RowIndex].Cells[1].Controls[0] as TextBox).Text;
        string sel = (gvResources.Rows[e.RowIndex].Cells[2].Controls[0] as TextBox).Text;

        DataRow dr = dtEditedResources.Rows.Find(key);

        if (dr != null)
        {
            dr["Default"] = def;
            dr["Selected"] = sel;
        }
        else
            dtEditedResources.Rows.Add(key, def, sel);

        Session["EditedResources"] = dtEditedResources;

        gvResources.EditIndex = -1;

        BindResources();
    }

    protected void gvResources_CancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvResources.EditIndex = -1;
        BindResources();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        SaveResources();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Session["EditedResources"] = null;
        BindResources();
    }

    protected void btnSaveCountry_Click(object sender, EventArgs e)
    {
        ShopModel.Settings.DefaultCountry = int.Parse(ddlDefaultCountry.SelectedValue);
        if (!ReportsManager.Instance.SaveSettings())
        {
            CtrlShowInfo.ShowInfo(true, Resources.Language.Cms_ErrorWhileSavingInDataBase);
            return;
        }
    }

    protected void LanguagesCommand(object sender, CommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "DeleteL":
                {
                    Language lang = ReportsManager.Instance.GetLanguageByID(Convert.ToInt32(e.CommandArgument));
                    if (!lang.IsDefault) //język domyślny nie może zostać usunięty
                    {
                        if (ReportsManager.Instance.DeleteLanguage(Convert.ToInt32(e.CommandArgument)))
                        {
                            try
                            {
                                string XmlDirectory = Settings.TemplatesDirectory + "/";

                                FileInfo fi = new FileInfo(Server.MapPath(XmlDirectory + "ContentTemplates." + lang.Culture + ".xml"));
                                fi.Delete();
                                fi = new FileInfo(Server.MapPath(@"~\App_GlobalResources\Language." + lang.Culture + ".resx"));
                                fi.Delete();
                                fi = new FileInfo(Server.MapPath(XmlDirectory + "NotificationTemplates." + lang.Culture + ".xml"));
                                fi.Delete();
                                CtrlShowInfo.ShowInfo(false, Resources.Language.LanguageDeleted );
                            }
                            catch (Exception ex)
                            {
                                CtrlShowInfo.ShowInfo(true, ex.Message);
                                return;

                            }
                        }
                        else
                        {
                            CtrlShowInfo.ShowInfo(true, Resources.Language.CmsProductEditMessage14);
                            return;
                        }

                    }
                    else
                    {
                        CtrlShowInfo.ShowInfo(true, Resources.Language.Cms_CantDeleteDefaultLanguage);
                        return;
                    }
                    break;
                }
            case "EditL":
                {
                    Language lang = ReportsManager.Instance.GetLanguageByID(Convert.ToInt32(e.CommandArgument));
                    LangNameTB.Text = lang.Name;
                    LangCultureTB.Text = lang.Culture;
                    LangActiveCB.Checked = lang.Active;
                    LangFlagUrlTB.Text = lang.FlagUrl;
                    LangIsDefaultCB.Checked = lang.IsDefault;
                    LangAddBTN.Text = Resources.Language.Save;
                    LangCancelBTN.Text = Resources.Language.Cancel;
                    Session[LANGUAGE_ID] = lang.LanguageID;
                    Session[EDIT_LANGUAGE_CULTURE] = lang.Culture;
                    return;
                }
            case "SetDefaultL":
                {
                    if (Session[DEFAULT_LANGUAGE_CULTURE] == null)
                    {
                        List<Language> languages = ReportsManager.Instance.GetAvailableLanguages(false);
                        for (int i = 0; i < languages.Count; i++)
                        {
                            if (languages[i].IsDefault) { Session[DEFAULT_LANGUAGE_CULTURE] = languages[i].Culture; break; }
                        }
                    }
                    if (ReportsManager.Instance.SetLanguageAsDefault(Convert.ToInt32(e.CommandArgument)))
                    {
                        try
                        {
                            string XmlDirectory = Settings.TemplatesDirectory + "/";

                            // kopiowanie danych konfiguracyjnych z dotychczasowego języka domyślnego do nowego
                            Language lang = ReportsManager.Instance.GetLanguageByID(Convert.ToInt32(e.CommandArgument));


                            // aktualny domyslny do nazwy z kulturą
                            FileInfo fi = new FileInfo(Server.MapPath(XmlDirectory + "ContentTemplates.xml"));
                            fi.MoveTo(Server.MapPath(XmlDirectory + "ContentTemplates." + (string)Session[DEFAULT_LANGUAGE_CULTURE] + ".xml"));
                            fi = new FileInfo(Server.MapPath(@"~\App_GlobalResources\Language.resx"));
                            fi.MoveTo(Server.MapPath(@"~\App_GlobalResources\Language." + (string)Session[DEFAULT_LANGUAGE_CULTURE] + ".resx"));
                            fi = new FileInfo(Server.MapPath(XmlDirectory + "NotificationTemplates.xml"));
                            fi.MoveTo(Server.MapPath(XmlDirectory + "NotificationTemplates." + (string)Session[DEFAULT_LANGUAGE_CULTURE] + ".xml"));
                            //nowy domyslny do nowej nazwy bez kultury
                            fi = new FileInfo(Server.MapPath(XmlDirectory + "ContentTemplates." + lang.Culture + ".xml"));
                            fi.MoveTo(Server.MapPath(XmlDirectory + "ContentTemplates.xml"));
                            fi = new FileInfo(Server.MapPath(@"~\App_GlobalResources\Language." + lang.Culture + ".resx"));
                            fi.MoveTo(Server.MapPath(@"~\App_GlobalResources\Language.resx"));
                            fi = new FileInfo(Server.MapPath(XmlDirectory + "NotificationTemplates." + lang.Culture + ".xml"));
                            fi.MoveTo(Server.MapPath(XmlDirectory + "NotificationTemplates.xml"));
                            //
                            CtrlShowInfo.ShowInfo(false, Resources.Language.LanguageSetAsDefault);
                            Session[DEFAULT_LANGUAGE_CULTURE] = lang.Culture;
                        }
                        catch (Exception ex)
                        {
                            CtrlShowInfo.ShowInfo(true, ex.Message);
                            return;
                        }
                    }
                    else
                    {
                        CtrlShowInfo.ShowInfo(true, Resources.Language.CmsProductEditMessage14);
                        return;
                    }
                    break;
                }
            case "AddL":
                {
                    if (Session[LANGUAGE_ID] == null) //dodanie
                    {
                        Language lang = new Language(null, LangNameTB.Text, LangCultureTB.Text, LangActiveCB.Checked, LangFlagUrlTB.Text, false, string.Empty);
                        if (ReportsManager.Instance.AddLanguage(lang))
                        {
                            CtrlShowInfo.ShowInfo(false, Resources.Language.LanguageAdded );
                        }
                        else
                        {
                            CtrlShowInfo.ShowInfo(true, Resources.Language.CmsProductEditMessage14);
                            return;
                        }
                    }
                    else //edycja
                    {
                        Language oldLanguage = ReportsManager.Instance.GetLanguageByID((int)Session[LANGUAGE_ID]);
                        Language lang = new Language((int)Session[LANGUAGE_ID], LangNameTB.Text, LangCultureTB.Text, LangActiveCB.Checked, LangFlagUrlTB.Text, false, string.Empty);

                        string XmlDirectory = Settings.TemplatesDirectory + "/";

                        if (ReportsManager.Instance.UpdateLanguage(lang))
                        {
                            if (LangCultureTB.Text != (string)Session[EDIT_LANGUAGE_CULTURE])//jeśli zmieniono kod kultury języka - zmiana nazw plików
                            {
                                try
                                {
                                    FileInfo fi;
                                    if (!oldLanguage.IsDefault) // jeśli język nie był domyślny
                                    {
                                        fi = new FileInfo(Server.MapPath(XmlDirectory + "ContentTemplates." + (string)Session[EDIT_LANGUAGE_CULTURE] + ".xml"));
                                        fi.MoveTo(Server.MapPath(XmlDirectory + "ContentTemplates." + LangCultureTB.Text + ".xml"));
                                        fi = new FileInfo(Server.MapPath(@"~\App_GlobalResources\Language." + (string)Session[EDIT_LANGUAGE_CULTURE] + ".resx"));
                                        fi.MoveTo(Server.MapPath(@"~\App_GlobalResources\Language." + LangCultureTB.Text + ".resx"));
                                        fi = new FileInfo(Server.MapPath(XmlDirectory + "NotificationTemplates." + (string)Session[EDIT_LANGUAGE_CULTURE] + ".xml"));
                                        fi.MoveTo(Server.MapPath(XmlDirectory + "NotificationTemplates." + LangCultureTB.Text + ".xml"));
                                        CtrlShowInfo.ShowInfo(false, Resources.Language.LanguageDataChanged);
                                    }
                                    else // jeśli zmieniliśmy kulturę domyślnego języka(nie trzeba zmieniać kodu kultury w nazwach)
                                    {
                                        CtrlShowInfo.ShowInfo(false, Resources.Language.LanguageDataChanged);
                                        ClearNewLanguageRow();
                                        gvLanguagesDataBind();
                                        return;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    CtrlShowInfo.ShowInfo(true, ex.Message);
                                    return;
                                }
                            }
                            else
                            {
                                CtrlShowInfo.ShowInfo(false, Resources.Language.LanguageDataChanged);
                                ClearNewLanguageRow();
                                gvLanguagesDataBind();
                                return;
                            }
                        }
                        else
                        {
                            CtrlShowInfo.ShowInfo(true, Resources.Language.CmsProductEditMessage14);
                            return;
                        }
                    }
                    ClearNewLanguageRow();
                    break;
                }
            case "CancelL":
                {
                    ClearNewLanguageRow();
                    return;
                }
        }
        Response.Redirect("Config.aspx?tab=1");
    }

    #endregion EVENTS

    #region PAGE EVENTS

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindLanguages();
            BindResources();
            Session["EditedResources"] = null;
            
            ddlCountryDataBind();            
            gvLanguagesDataBind();
        }
    }

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        btnSave.Enabled = Session["EditedResources"] != null;
        btnCancel.Enabled = Session["EditedResources"] != null;
    }

    #endregion PAGE EVENTS


}
